<?php

namespace Controller;

use Controller\App,
    Lib\Controller\Auth,
    Lib\Dispatcher,
    Lib\Request,
    Lib\Util\Util,
    Lib\Util\Session;

class Admin extends App {

    public $layout = 'admin';
    public $title  = 'Администрација';

    public function __construct($request) {
        parent::__construct($request);

        Auth::secure($this);

        $this->loadAdminMenu();
    }

    public function index() {
        $this->title .= ' &raquo; Подешавања';
        $this->loadModel('Setting');
        $this->set('data', $this->Setting->find());
    }

    public function save() {
        $data = Request::post('data');
        if (! empty($data)) {
            $this->loadModel('Setting');
            if ($saved = $this->Setting->saveAll($data)) {
                Session::flash('Сачувано.', 'ok');
            } else {
                if (! empty($this->Setting->error)) {
                    Session::flash('Грешка: ' . $this->Setting->error, 'error');
                }
            }
        }

        $this->redirect('/admin');
    }

    public function login() {
        if (Auth::authorized())
            $this->redirect(Request::referer('/admin'));

        $data = Request::post();
        if ($data) {
            if (! Auth::authorize($this, Request::post())) {
                Session::flash('Пријава није успела. Покушајте поново.', 'error');
            }
            $this->redirect('/admin');
        }
    }

    public function logout() {
        Auth::unauthorize();
        return $this->redirect('/admin');
    }

    private function loadAdminMenu() {
        $menu = json_decode(file_get_contents(DIR_CONFIG . DS . 'menu_admin.json'));
        
        foreach ($menu as &$item) {
            $item->active = Request::isActive($item->link);
        }

        $this->set('menu', $menu);
    }
}